<template>
  <div class="carousel" >
    <div v-mouseover="{autoPlay, closeAutoPlay}">
      <slot></slot>
      <div class="dots" v-if="hasDot">
        <Dot
            :curItem="curItem"
            :itemLen="itemLen"
            :bgColor="bgColor"
            v-for="i in itemLen"
            :key="i"
            @handleClick="handleClick"
        ></Dot>
      </div>
    </div>
  </div>

</template>

<script>
import {getCurrentInstance, onMounted, onUnmounted, reactive, toRefs} from "vue";
import Dot from "./Dot";

export default {
  name: "KCarousel",
  components: {Dot},
  props: {
    autoplay: {
      type: Boolean,
      default: true,
    },
    duration: {
      type: Number,
      default: 3000,
    },
    initial: {
      type: Number,
      default: 0,
    },
    hasDot: {
      type: Boolean,
      default: true,
    },
    bgColor: {
      type: String,
      default: "black",
    },
    hasDirector: {
      type: Boolean,
      default: true,
    },
  },
  setup(props) {
    const instance = getCurrentInstance()

    let state = reactive({
      curItem: props.initial,
      itemLen: instance.slots.default()[0].children.length
    })

    let t = null

    const autoPlay = () => {
      if(props.autoplay) {
        t = setInterval(() => {
          setIndex('r')
        }, props.duration)
      }
    }

    //闭包
    const closeAutoPlay = () => {
      clearInterval(t);
    }

    const handleClick = (value) => {
      state.curItem = value
    }

    const setIndex = (dir) => {
      switch (dir) {
        case 'r':
          state.curItem += 1;
          if(state.curItem === state.itemLen) {
            state.curItem = 0;
          }
          break
        case 'l':
          state.curItem -= 1;
          if(state.curItem === -1) {
            state.curItem = state.itemLen - 1;
          }
          break
        default:
          break
      }
    }

    onMounted(() => {
      autoPlay();
    })

    onUnmounted(() => {
      clearInterval(t);
    })

    return {
      ...toRefs(state),
      handleClick,
      autoPlay,
      closeAutoPlay,
    }
  },
  directives: {
    mouseover: {
      mounted(el, binding) {
        el.addEventListener('mouseover', binding.value.closeAutoPlay)
        el.addEventListener('mouseleave', binding.value.autoPlay)
      }
    }
  },
}
</script>

<style scoped>

.carousel {
  position: relative;
  top: 0;
  left: 0;
  height: 100%;

  overflow: hidden;
}

.dots {
  position: absolute;
  bottom: 0;
  left: 50%;

  transform: translateX(-50%);
}

</style>